package controller

import (
	"Library_Management_System/API"
	"html/template"
	"net/http"
	"strconv"
)

// GetUserBook 转到图书借阅页面
func GetUserBook(w http.ResponseWriter, r *http.Request) {
	books, err := API.GetAllBooks()
	if err != nil {
		panic(err.Error())
	}
	t, err := template.ParseFiles("views/pages/pageUser_book.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = t.Execute(w, books)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

// GetAdminBook 转到图书管理页面
func GetAdminBook(w http.ResponseWriter, r *http.Request) {
	books, err := API.GetAllBooks()
	if err != nil {
		panic(err.Error())
	}
	t, err := template.ParseFiles("views/pages/pageAdmin_book.html")
	if err != nil {
		panic(err.Error())
	}
	err = t.Execute(w, books)
	if err != nil {
		panic(err.Error())
	}
}

// GetAdminUser 转到用户管理页面
func GetAdminUser(w http.ResponseWriter, r *http.Request) {
	users, err := API.GetAllUsersInfo()
	if err != nil {
		panic(err.Error())
	}
	t := template.Must(template.ParseFiles("views/pages/pageAdmin_user.html"))
	err = t.Execute(w, users)
	if err != nil {
		panic(err.Error())
	}
}

// GetAllBorrowInfo 获取用户借阅信息
func GetAllBorrowInfo(w http.ResponseWriter, r *http.Request) {
	borrowInfo, err := API.GetAllBorrowInfo()
	if err != nil {
		panic(err.Error())
	}
	t := template.Must(template.ParseFiles("views/pages/pageAdmin_borrow.html"))
	err = t.Execute(w, borrowInfo)
	if err != nil {
		panic(err.Error())
	}
}

// GetBooksByCriteria 根据筛选条件获取图书信息
func GetBooksByCriteria(w http.ResponseWriter, r *http.Request) {
	// 获取筛选条件
	title := r.PostFormValue("title")
	author := r.PostFormValue("author")
	minPrice := r.PostFormValue("minPrice")
	var minPriceFloat float64
	var err error
	if minPrice == "" {
		minPriceFloat = 0
	} else {
		minPriceFloat, err = strconv.ParseFloat(minPrice, 64)
		if err != nil {
			panic(err.Error())
		}
	}
	maxPrice := r.PostFormValue("maxPrice")
	var maxPriceFloat float64
	if maxPrice == "" {
		maxPriceFloat = 0
	} else {
		maxPriceFloat, err = strconv.ParseFloat(maxPrice, 64)
		if err != nil {
			panic(err.Error())
		}
	}
	isAdmin, err := strconv.ParseBool(r.PostFormValue("isAdmin"))

	// 获取筛选过后的图书
	books, err := API.GetBooksByCriteria(title, author, minPriceFloat, maxPriceFloat)
	if err != nil {
		panic(err.Error())
	}
	if isAdmin {
		t := template.Must(template.ParseFiles("views/pages/pageAdmin_book.html"))
		err = t.Execute(w, books)
		if err != nil {
			panic(err.Error())
		}
	} else {
		t := template.Must(template.ParseFiles("views/pages/pageUser_book.html"))
		err = t.Execute(w, books)
		if err != nil {
			panic(err.Error())
		}
	}
}
